var express = require("express");
var router = express.Router();
const http = require("https");
const cheerio = require("cheerio");

const relatedData = require("../data/related");

let detailList = {};
let commentList = {};

router.get("/info", (req, res, next) => {
  if (req.query.id) {
    if (detailList[req.query.id]) {
      res.json({
        success: true,
        data: detailList[req.query.id],
      });
    } else {
      const req2 = http.request(
        {
          hostname: `view.inews.qq.com`,
          port: 443,
          path: `/k/${req.query.id}?web_channel=wap&openApp=false`,
          method: "GET",
          headers: {
            "Content-Type": "text/html",
          },
        },
        (res2) => {
          let str = "";
          res2.on("data", (d) => {
            if (res2.statusCode === 301 || res2.statusCode === 302) {
              const redirectUrl = res2.headers.location;
              const parsedUrl = new URL(redirectUrl);
              const req3 = http.request(
                {
                  hostname: parsedUrl.hostname,
                  port: parsedUrl.port || 443,
                  path: parsedUrl.pathname + parsedUrl.search,
                  method: "GET",
                  headers: {
                    "Content-Type": "text/html",
                  },
                },
                (res3) => {
                  let str = "";
                  res3.on("data", (d) => {
                    str += d;
                  });
                  res3.on("end", () => {
                    // detailList[req.query.id] = JSON.parse(str);
                    const $ = cheerio.load(str);
                    let result = "";
                    // 找到所有的 script 标签
                    const scripts = $("script");
                    // 遍历 script 标签，提取内容
                    scripts.each((i, element) => {
                      const scriptContent = $(element).text();
                      if (scriptContent.includes("window.DATA")) {
                        result = JSON.parse(
                          scriptContent
                            .match(/window\.DATA = (.*)/)[1]
                            .slice(0, -1)
                        );
                      }
                    });
                    detailList[req.query.id] = result;
                    res.json({
                      success: true,
                      data: result,
                    });
                  });
                }
              );
              req3.on("error", (error) => {
                console.error(error);
              });
              req3.end();
            }
            str += d;
          });
        }
      );
      req2.on("error", (error) => {
        console.error(error);
      });
      req2.end();
    }
  } else {
    res.json({ success: false, msg: "参数错误" });
  }
});

router.get("/related", (req, res, next) => {
  res.json({
    success: true,
    data: relatedData,
  });
});

router.get("/comment", function (req, res, next) {
  if (req.query.id) {
    if (commentList[req.query.id]) {
      res.json({
        success: true,
        data: commentList[req.query.id],
      });
    } else {
      const req2 = http.request(
        {
          hostname: `view.inews.qq.com`,
          port: 443,
          path: `/getQQNewsComment?article_id=${req.query.id}&reqNum=15&transparam=&devid=75637b7e46d6b77d&currentChannelId=news_news_share`,
          method: "GET",
          headers: {
            "Content-Type": "application/json",
          },
        },
        (res2) => {
          let str = "";

          res2.on("data", (d) => {
            str += d;
          });

          res2.on("end", () => {
            commentList[req.query.id] = JSON.parse(str);
            res.json({
              success: true,
              data: JSON.parse(str),
            });
          });
        }
      );

      req2.on("error", (error) => {
        console.error(error);
      });

      req2.end();
    }
  } else {
    res.json({ success: false, msg: "参数错误" });
  }
});

module.exports = router;
